const express=require('express')
const path=require('path')
const db=require('./db/connect')
const app=express()
//设置接口权限
const cookie=require('cookie-parser')
const session=require('express-session')
app.use(session({
    secret:'sjfsdkjflajf',//为了安全性设置seCRET
    cookie:{maxAge:60*1000*24},//设置过期时间
    resave:true,
    saveUninitialized:false,//每次请求都会设置新的session cookie
}))

//跨域问题
const cors=require('cors')
app.use(cors())


//中间件
const body =require('body-parser')
app.use(body.json())
app.use(body.urlencoded({extended:true}))



//静态资源目录
app.use('/public',express.static(path.join(__dirname,'static')))

//上传图片
const filerouter=require('./router/filerouter')
app.use('/file',filerouter)


//引入路由
const userrouter=require('./router/userRouter')
const foodrouter=require('./router/foodRouter')
const { route } = require('./router/foodRouter')
const router = require('./router/foodRouter')




let sess=null
app.use('/user',(req,res,next)=>{
    sess=req
    console.log(req.session)
    console.log(req.body)
    next()
    
},userrouter)
//清除cookie
app.post('/out',(req,res)=>{
    sess.session.destroy()//删除保存的session
    res.send({err:0,msg:'退出'})
    console.log('ok')
})


app.use('/food',(req,res,next)=>{
    //设置登录验证
    console.log(req.body)
    if(sess!==null){
        if(sess.session.login){
            next()
        }else{
            res.send({err:-110,msg:'cookie过期'})
        }
    }else{
        res.send({err:-110,msg:'请先登录'})
    }
    
    
},foodrouter)
app.listen(3000,()=>{
    console.log('server running')
})